package model.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import tools.excel.tool;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import dom.domain.Examplace;
import dom.domain.ExamplaceDAO;
import dom.domain.Generaltype;
import dom.domain.GeneraltypeDAO;
import dom.domain.Score;
import dom.domain.ScoreDAO;
import dom.domain.Subtype;
import dom.domain.SubtypeDAO;
import dom.domain.SubtypeId;
import dom.domain.User;
import dom.domain.UserDAO;

public class UserService {
	private UserDAO userDao;
	private ExamplaceDAO epDao;
	private GeneraltypeDAO gDao;
	private SubtypeDAO subDao;
	private ScoreDAO scoreDao;
	public static String registState = "0";// 注册状态
	private static String signState = "1";// 报名状态
	private static String admitState = "2";// 审核通过状态
	private Map<String, String> map;
	
	public void setEpDao(ExamplaceDAO epDao) {
		this.epDao = epDao;
	}

	public void setgDao(GeneraltypeDAO gDao) {
		this.gDao = gDao;
	}

	public void setSubDao(SubtypeDAO subDao) {
		this.subDao = subDao;
	}

	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

	public void setScoreDao(ScoreDAO scoreDao) {
		this.scoreDao = scoreDao;
	}

	/*
	 * public String changePsd(String userInfo) { map = new
	 * HashMap<String,String>(); try { JSONObject user =
	 * JSONObject.fromObject(userInfo); if(!user.containsKey("userId")) {
	 * map.put("flag", "false"); map.put("info","userId is empty"); return
	 * JSONObject.fromObject(map).toString(); } User tempUser =
	 * userDao.findById(user.getString("userId")); if(tempUser==null) {
	 * map.put("flag", "false"); map.put("info","用户名不存在！"); return
	 * JSONObject.fromObject(map).toString();
	 * 
	 * } if(user.containsKey("psd")) { tempUser.setPsd(user.getString("psd"));
	 * userDao.attachDirty(tempUser); map.put("flag", "true"); map.put("info",
	 * "修改成功"); } else { map.put("flag", "false"); map.put("info","密码不存在！"); }
	 * }catch(JSONException e) { map.put("flag","false"); map.put("info",
	 * "数据格式异常"); } return JSONObject.fromObject(map).toString(); }
	 */
	public String changeState(String userId, String state) {
		map = new HashMap<String, String>();
		User user = userDao.findById(userId);
		if (user == null) {
			map.put("flag", "flase");
			map.put("Info", "userId不存在");
			return JSONObject.fromObject(map).toString();
		}
		user.setState(state);
		userDao.attachDirty(user);
		map.put("flag", "true");
		map.put("Info", "success");
		return JSONObject.fromObject(map).toString();
	}
	public String changeState(String userIds){
		String[] users = userIds.split(",");
		StringBuilder result = new StringBuilder();
		for(int i=0;i<users.length;i++)
		{
			JSONObject jInfo = JSONObject.fromObject(changeState(users[i],admitState));
			if(!jInfo.getString("flag").equals("true"))
			{
				result.append(jInfo.getString("Info"));
			}
		}
		map.put("flag", "true");
		map.put("Info",result.toString());
		return JSONObject.fromObject(map).toString();
	}
	public String addUser(String userInfo)
	{
		map = new HashMap<String,String>();
		try
		{
			User user = new User();
			JSONObject jInfo = JSONObject.fromObject(userInfo);
			if(!jInfo.containsKey("userId"))
			{
				map.put("flag", "false");
				map.put("info", "userId 为空");
				return JSONObject.fromObject(map).toString();
			}
			if(!(jInfo.containsKey("email")&&jInfo.getString("userId").equals("")))
			{
				map.put("flag", "false");
				map.put("info", "email 为空");
				return JSONObject.fromObject(map).toString();
			}
			if(!jInfo.containsKey("name"))
			{
				map.put("flag", "false");
				map.put("Info", "name为空");
				return JSONObject.fromObject(map).toString();
			}
			user.setEmail(jInfo.getString("email"));
			if(jInfo.getString("userId").equals(""))
			{
				user.setUserId(jInfo.getString("email"));;
			}else
			{
				user.setUserId(jInfo.getString("userId"));
			}
			User temp = userDao.findById(user.getUserId());
			if(temp!=null)
			{
			map.put("flag", "false");
			map.put("Info", "用户名已存在");
			return JSONObject.fromObject(map).toString();
			}
			if(!jInfo.containsKey("psd"))
			{
				map.put("flag","false");
				map.put("Info", "psd为空");
				return JSONObject.fromObject(map).toString();
			}
			if(jInfo.getString("psd").equals(""))
			{
				user.setPsd(tool.getPassword());
			}
			else
			{
				user.setPsd(jInfo.getString("psd"));
			}
			if(!jInfo.containsKey("id"))
			{
				map.put("flag", "false");
				map.put("Info", "id 为空");
				return JSONObject.fromObject(map).toString();
			}
			if(!jInfo.containsKey("general"))
			{
				map.put("flag", "false");
				map.put("Info", "报考类别为空");
				return JSONObject.fromObject(map).toString();
			}
			if(!jInfo.containsKey("subtype"))
			{
				map.put("flag", "false");
				map.put("Info", "报考小类别为空");
				return JSONObject.fromObject(map).toString();
			}
			if(!jInfo.containsKey("eeid"))
			{
				map.put("flag","false");
				map.put("Info", "高考号为空");
				return JSONObject.fromObject(map).toString();
			}
			if(!jInfo.containsKey("state"))
			{
				map.put("flag","false");
				map.put("Info", "state为空");
				return JSONObject.fromObject(map).toString();
			}
			user.setName(jInfo.getString("name"));
			user.setEeid(jInfo.getString("eeid"));
			user.setId(jInfo.getString("id"));
			user.setUserGeneralType(jInfo.getString("general"));
			user.setUserSubType(jInfo.getString("subtype"));
			user.setState(jInfo.getString("state"));
			user.setProvinceId(Integer.parseInt(jInfo.getString("id").substring(0,2)));
			user.setEpyear(constant.constant.year);
			user.setAdmitIdAllocated(0);
			user.setEpAllocated(0);
			userDao.save(user);
			map.put("flag", "true");
			map.put("Info","success");
			
		}catch(JSONException e)
		{
			map.put("flag","false");
			map.put("Info",e.getMessage());
		}
		return JSONObject.fromObject(map).toString();
	}

	public String allocateRegistId() {
		map = new HashMap<String, String>();
		List list = userDao.findByAdmitIdAllocated(0);
		for (int i = 0; i < list.size(); i++) {
			StringBuilder registId = new StringBuilder(
					constant.constant.ECNUCode);
			User user = (User) list.get(i);
			registId.append(user.getProvinceId());
			registId.append(user.getUserGeneralType());
			if (user.getUserSubType().length() == 1) {
				registId.append("0" + user.getUserSubType());
			} else {
				registId.append(user.getUserSubType());
			}
			long count = userDao.getCount(1,
					user.getUserGeneralType(),
					user.getUserSubType(),
					user.getProvinceId());
			if (count + 1 < 10) {
				registId.append("000" + (count + 1));
			} else if (count + 1 < 100) {
				registId.append("00" + (count + 1));
			} else if (count + 1 < 1000) {
				registId.append("0" + (count + 1));
			} else {
				registId.append(count + 1);
			}
			user.setAdmitIdAllocated(1);
			user.setAdmitId(registId.toString());
			userDao.attachDirty(user);
		}
		
		map.put("flag", "true");
		map.put("Info", "success");
		return JSONObject.fromObject(map).toString();
	}
	public String deleteAll(String allUserId) {
		map = new HashMap<String, String>();
		String[] userIds = allUserId.split(",");
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < userIds.length; i++) {
			JSONObject jresult = JSONObject.fromObject(delete(userIds[i]));
			if (jresult.getString("flag").equals("false"))
				result.append(jresult.getString("Info"));
		}
		map.put("flag", "true");
		map.put("Info", result.toString());
		return JSONObject.fromObject(map).toString();

	}

	public String getList(int pageNum) {
		map = new HashMap<String, String>();
		List list = userDao.getList(pageNum, 10);
		JSONArray array = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			User user = (User) list.get(i);
			JSONObject jInfo = JSONObject.fromObject(user.getString());
			if(user.getUserGeneralType()!=null&&user.getUserSubType()!=null)
			{
			Subtype subtype = subDao.findById(new SubtypeId(Integer.parseInt(user.getUserGeneralType()),Integer.parseInt(user.getUserSubType())));
			Generaltype gType = gDao.findById(Integer.parseInt(user.getUserGeneralType()));
			jInfo.put("general", gType.getName());
			jInfo.put("subtype", subtype.getName());
			}else
			{
				jInfo.put("general","");
				jInfo.put("subtype", "");
			}
			array.add(jInfo);
		}
		if(array.size()==0)
		{
			map.put("flag", "false");
			map.put("Info","未添加任何数据");
			return JSONObject.fromObject(map).toString();
		}
		map.put("flag", "true");
		map.put("Info", "success");
		map.put("list", array.toString());
		map.put("size", Integer.toString(array.size()));
		return JSONObject.fromObject(map).toString();
	}
	
	public String queryByName(String name)
	{
		map = new HashMap<String,String>();
		List list = userDao.query(name);
		JSONArray array = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			User user = (User) list.get(i);
			JSONObject jInfo = JSONObject.fromObject(user.getString());
			if(user.getUserGeneralType()!=null&&user.getUserSubType()!=null)
			{
			Subtype subtype = subDao.findById(new SubtypeId(Integer.parseInt(user.getUserGeneralType()),Integer.parseInt(user.getUserSubType())));
			Generaltype gType = gDao.findById(Integer.parseInt(user.getUserGeneralType()));
			jInfo.put("general", gType.getName());
			jInfo.put("subtype", subtype.getName());
			}else
			{
				jInfo.put("general","");
				jInfo.put("subtype", "");
			}
			array.add(jInfo);
		}
		if(array.size()==0)
		{
			map.put("flag", "false");
			map.put("Info","未查到任何数据");
			return JSONObject.fromObject(map).toString();
		}
		map.put("flag", "true");
		map.put("Info", "success");
		map.put("list", array.toString());
		map.put("size", Integer.toString(array.size()));
		return JSONObject.fromObject(map).toString();
	}

	public String ChooseEP(String userId, int epId) {
		map = new HashMap<String, String>();
		if (userId != null) {
			User user = userDao.findById(userId);
			if (user == null) {
				map.put("flag", "false");
				map.put("Info", "用户民不存在");
				return JSONObject.fromObject(map).toString();
			}
			Examplace ep = epDao.findById(epId);
			if (ep == null) {
				map.put("flag", "false");
				map.put("Info", "考场号不存在");
				return JSONObject.fromObject(map).toString();
			}

			if (epDao.update(epId)) {
				user.setEpId(ep.getEpId());
				user.setEpAllocated(1);
				userDao.attachDirty(user);
				map.put("flag", "true");
				map.put("Info", "选择成功");
			} else {
				map.put("flag", "false");
				map.put("Info", "该考点人数已满");
			}
		}
		return JSONObject.fromObject(map).toString();
	}

	// 分配考点
	public String allocateEP(User user) {
		if (user == null) {
			return "non-existent";
		}
		List list = epDao.findByProvinceId(user.getProvinceId());
		if (list.size() == 0) {
			return "ep_non-existent";
		}
		for (int i = 0; i < list.size(); i++) {
			Examplace ep = (Examplace) list.get(i);
			if (ep.getAllocatedNo() < ep.getLimitNo()) {
				ep.setAllocatedNo(ep.getAllocatedNo() + 1);
				user.setEpId(ep.getEpId());
				user.setEpAllocated(1);;
//				user.setAuthority(1);
				epDao.attachDirty(ep);
				userDao.attachDirty(user);
				return "success";
			}
		}
		return "not_find";
	}

	public String allocatedAll() {
		map = new HashMap<String, String>();
		List list = userDao.query(0, "2");
		StringBuilder log = new StringBuilder();
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				User user = (User) list.get(i);
				String temp;
				if (!(temp = allocateEP(user)).equals("success")) {
					log.append(user.getUserId() + ":" + temp + ",");
				}
			}
		}
		map.put("flag", "true");
		map.put("Info", log.toString());
		return JSONObject.fromObject(map).toString();
	}

	public String delete(String userId) {
		map = new HashMap<String, String>();
		if (userId == null) {
			map.put("flag", "false");
			map.put("info", "用户名为空");
			return JSONObject.fromObject(map).toString();
		}
		User tempUser = userDao.findById(userId);
		if (tempUser == null) {
			map.put("flag", "false");
			map.put("info", "用户名不存在");
		} else {
			userDao.delete(tempUser);
			map.put("flag", "true");
			map.put("info", "删除成功");
		}
		return JSONObject.fromObject(map).toString();
	}

	public String query(String userId) {
		map = new HashMap<String, String>();
		if (userId == null) {

			map.put("flag", "false");
			map.put("info", "用户名为空");
			return JSONObject.fromObject(map).toString();
		}
		User tempUser = userDao.findById(userId);
		if (tempUser == null) {
			map.put("flag", "false");
			map.put("info", "用户名不存在");
		} else {
			map.put("userInfo", JSONObject.fromObject(tempUser.toString())
					.toString());
			map.put("epState", Integer.toString(tempUser.getEpAllocated()));
			System.out.println(tempUser.getGender());
			if (tempUser.getEpId() != null) {
				Examplace ep = epDao.findById(tempUser.getEpId());
				if (ep != null) {
					map.put("ep", ep.getEpname());
					map.put("epAddress", ep.getEpAddress());
				} else {
					map.put("ep", "");
					map.put("epAddress", "");
				}
			} else {
				map.put("ep", "");
				map.put("epAddress", "");
			}
			Score score = scoreDao.findById(userId);
			if (score == null) {
				map.put("score", "暂无成绩");
			} else {
				map.put("score", Double.toString(score.getScore()));
			}
			if (tempUser.getUserGeneralType() != null) {
				Generaltype gType = gDao.findById(Integer.parseInt(tempUser
						.getUserGeneralType()));
				if (gType != null) {
					Subtype sType = subDao.findById(new SubtypeId(Integer
							.parseInt(tempUser.getUserGeneralType()), Integer
							.parseInt(tempUser.getUserSubType())));
					if (sType != null) {
						map.put("general", gType.getName());
						map.put("sub", sType.getName());
					} else {
						map.put("general", "未选择");
						map.put("sub", "未选择");
					}

				} else {
					map.put("general", "未选择");
					map.put("sub", "未选择");
				}
			} else {
				map.put("general", "");
				map.put("sub", "");
			}
			map.put("flag", "true");
			map.put("info", "查询成功");
		}
		return JSONObject.fromObject(map).toString();
	}

	// 报名
	public String changeInfo(String userInfo,String operation) {
		map = new HashMap<String, String>();
		try {
			JSONObject user = JSONObject.fromObject(userInfo);
			if (!user.containsKey("userId")) {
				map.put("flag", "false");
				map.put("info", "userId is empty");
				return JSONObject.fromObject(map).toString();
			}
			User tempUser = userDao.findById(user.getString("userId"));
			if (tempUser == null) {
				map.put("flag", "false");
				map.put("info", "用户名不存在！");
				return JSONObject.fromObject(map).toString();
			}
			if(user.containsKey("name"))
			{
				tempUser.setName(user.getString("name"));
				
			}
			if (user.containsKey("eeid")) {
				tempUser.setEeid(user.getString("eeid"));
			}
			if (user.containsKey("id")) {
				tempUser.setId(user.getString("id"));
				tempUser.setProvinceId(Integer.parseInt(user.getString("id").substring(0,2)));
			}
			if (user.containsKey("phoneNo")) {
				tempUser.setPhoneNo(user.getString("phoneNo"));
			}
			if (user.containsKey("userGeneralType")) {
				tempUser.setUserGeneralType(user.getString("userGeneralType"));
			}
			if (user.containsKey("userSubType")) {
				tempUser.setUserSubType(user.getString("userSubType"));
			}
			if (user.containsKey("userDescribe")) {
				tempUser.setUserDescribe(user.getString("userDescribe"));
			}
			if (user.containsKey("birthday")) {
				tempUser.setBirthday(user.getString("birthday"));
			}
			if (user.containsKey("policy")) {
				tempUser.setPolicy(user.getString("policy"));
			}
			if (user.containsKey("nation")) {
				tempUser.setNation(user.getString("nation"));
			}
			if (user.containsKey("EPyear")) {
				tempUser.setEpyear(user.getString("EPyear"));
			}
			if (user.containsKey("epId")) {
				tempUser.setEpId(Integer.parseInt(user.getString("epId")));
			}
			if (user.containsKey("gender")) {
				tempUser.setGender(user.getString("gender"));
			}
			if(operation.equals("modify"))
			{
				if(user.containsKey("state"))
				{
					tempUser.setState(user.getString("state"));
				}
				if(user.containsKey("psd"))
				{
					tempUser.setPsd(user.getString("psd"));
				}
			}
			else
			{
				tempUser.setState(signState);
			}
			userDao.attachDirty(tempUser);
			map.put("flag", "true");
			map.put("info", "修改成功");
		} catch (JSONException e) {
			map.put("flag", "false");
			map.put("info", e.getMessage());
		}
		return JSONObject.fromObject(map).toString();
	}

}
